<template>
  <view class="container">
    <view class="step-wrap">
      <ve-steps :list="stepList" :active="activeStepListIndex" />
    </view>
    <view class="order-relet-content" :style="{ 'padding-bottom': activeStepListIndex == 0 ? '130rpx' : '360rpx' }">
      <summary-info title="租赁信息" :summaryList="summaryLease" :defaultFold="false">
        <template #leasePeriod>
          <view class="lease-period">
            <view class="lease-period-val">{{
              orderInfo.expectedUseCarTime ? `${orderInfo.expectedUseCarTime} - ${orderInfo.expectedReturnCarTime}` : '-'
            }}</view>
            <view class="lease-period-rentdays" v-if="orderInfo.leaseNumberStr">租期：{{ orderInfo.leaseNumberStr }}</view>
          </view>
        </template>
      </summary-info>
      <view v-show="activeStepListIndex == 0">
        <ve-form :model="form" layout="vertical" :rules="rules" ref="formRef">
          <ve-card class="relet-info" title="续租信息">
            <ve-form-item prop="endTime" required label="续租后还车时间">
              <ve-date-picker
                v-model="form.endTime"
                valueFormat="YYYY-MM-DD 23:59:59"
                mode="date"
                :minDate="orderInfo.expectedReturnCarTime"
                @confirm="calcRentDays"
              />
              <template #rightContent>
                <view class="rent-days"> 续租时长：{{ leaseNumberStr || '- 天' }} </view>
              </template>
            </ve-form-item>
            <ve-form-item label="续租备注" :borderBottom="false" labelPosition="top">
              <ve-input type="textarea" v-model="form.remark" :maxlength="200" />
            </ve-form-item>
          </ve-card>
        </ve-form>
        <contract-card />
      </view>
      <!-- 费用信息 -->
      <view class="fee-pane-content" v-show="activeStepListIndex == 1">
        <ve-form :model="feeForm" ref="feeFormRef" layout="vertical" :rules="feeFormRules">
          <ve-card title="续租费用" fold>
            <template v-for="(item, index) in feeForm.orderFee" :key="index">
              <fee-pane
                :isReletOrder="true"
                :orderFormType="'reletOrder'"
                :orderFeeIndex="index"
                :inlineCard="true"
                :disabledOnlineFee="true"
                @feeChange="feeChangeFn"
              />
            </template>
          </ve-card>
          <!-- 收款方式 -->
          <!-- 费用大于0，且租期大于等于一个月 -->
          <order-payment-pane v-if="feeRealtimeSum > 0 && leaseMonthsNumber > 0" :contractAmount="feeRealtimeSum" :fold="true" />
        </ve-form>
      </view>
    </view>
    <!-- 二次确认 -->
    <ve-confirm titleText="请确认是否排车？" v-model="confirmVisible" @confirm="confirmSubmit">
      <view v-for="(it, i) in resultMsg" :key="i">{{ it }}</view>
    </ve-confirm>
    <footer-box id="footer-box">
      <block v-if="activeStepListIndex == 0">
        <ve-button size="long" type="primary" :disabled="!nextStepIsValid" @click="stepClickFn">下一步 去完善费用信息</ve-button>
      </block>
      <template #extra v-if="activeStepListIndex == 1">
        <feeStatistic feeSummaryTitle="续租费用信息" :showOriginFeeStatics="true" :originSumInfo="originSumInfo" />
      </template>
      <block v-if="activeStepListIndex == 1">
        <ve-button type="plain" @click="stepClickFn">上一步</ve-button>
        <ve-button type="primary" :loading="okLoading" @click="submitFn">完成</ve-button>
      </block>
    </footer-box>
  </view>
</template>
<script setup name="ShortOrderReletOrder">
  import { ref, provide, computed, nextTick } from 'vue'
  import {
    computeRentDayAPI,
    getOrdrDetailsAPI,
    reletOrderAPI,
    calcPriceAPI,
    platoonCarCheckAPI,
    getOrdrFeeDetailAPI,
  } from '@/api/order/lOrder'
  import summaryInfo from './components/summary-info.vue'
  import feePane from './components/order-fee/fee-pane.vue'
  import footerBox from './form/components/footerBox.vue'
  import feeStatistic from './components/order-fee/fee-statistic.vue'
  import orderPaymentPane from './components/order-payment-pane.vue'
  import contractCard from './components/contract/contract-card.vue'
  import {
    buildCostInfoParam,
    initFeeDetail,
    getStoreTemplateDetail,
    handleStoreTemplateDetail,
    getOrderFeeRules,
    handleAddserviceDefaultFee,
  } from './components/order-fee/fee-utils.js'
  import { decimalAddition } from '@/utils'
  import { buildTreeData, processTreeData } from './components/order-fee/fee-statistic.js'
  import useFormFold from '@/hooks/useFormFold'
  import dayjs from 'dayjs'
  import { onLoad } from '@dcloudio/uni-app'
  const { foldValidate } = useFormFold([])
  import useToast from '@/hooks/useToast'
  import { userStore } from '@/stores'
  const userInfoStore = userStore()
  userInfoStore.setEpDetail(false)
  console.log(userInfoStore, 'userInfoStore')
  import { useLoadDataAndHotUpdateNavigateBack } from '@/hooks/useListNavigate'

  const form = ref({})
  const orderInfo = ref({})
  const orderId = ref()
  onLoad((options) => {
    orderId.value = options.id
    form.value = {
      id: orderId.value,
      // 默认选中分期
      paymentScheme: 2,
      // 默认分期方式
      paymentMethod: 2,
      // 首期付款日默认值
      lnstalmentFirstDate: dayjs().format('YYYY-MM-DD'),
      // 合同信息
      contractList: [{ contractTypeName: '续租合同' }],
    }
    // 初始化
    init()
  })

  const stepList = ['续租信息', '续租费用信息']
  const activeStepListIndex = ref(0)
  // 费用变化
  const feeChangeFn = (item, val, index) => {
    if ((val || val == 0) && val != '') {
      let feeDetailList = feeForm.value.orderFee[0].feeDetailList
      let option = feeDetailList[index].childrenList
      let itemName = item.itemName
      if (itemName == '月租价（标准）') {
        let target = option.find((item) => item.itemName == '车辆租金')
        if (target) target.amount = val * calcRate.value
      }
      if (itemName == '手续费（标准）') {
        let target = option.find((item) => item.itemName == '手续费')
        if (target) target.amount = val * 1
      }
      if (itemName == '基础保险（标准）') {
        let target = option.find((item) => item.itemName == '基础保险')
        if (target) target.amount = val * calcRate.value
      }
    }
  }

  // 处理默认值
  // 租赁周期限制最小时长 60 分钟
  const timeRangeValidator = (rule, value, callback) => {
    if (value) {
      let start = orderInfo.value.endTime
      let end = value
      if (start && end) {
        let diff = dayjs(end).diff(dayjs(start))
        if (diff < 60 * 60 * 1000) {
          callback('续租时长最短为1小时')
        }
      }
    }
    callback()
  }
  const rules = computed(() => {
    let _rule = {
      endTime: [{ required: true, message: '请选择续租后还车时间' }, { validator: timeRangeValidator }],
    }
    // 合同编号必填项
    let contractList = form.value.contractList
    if (contractList[0].fileId) {
      _rule['contractList.0.contractNo'] = [{ required: true, message: '请输入合同编号' }]
    }
    return _rule
  })

  // 表单规则
  const feeFormRules = computed(() => {
    return getOrderFeeRules(feeForm.value.orderFee)
  })

  const formRef = ref()
  provide('form', form)

  // 顶部统计信息
  const summaryLease = computed(() => {
    const orderInfoVal = orderInfo.value
    return [
      { label: '预计租赁周期', slotName: 'leasePeriod' },
      { label: '交车车牌号', value: orderInfoVal.licenseNo },
      { label: '预订车型', value: orderInfoVal.originalModelName },
      { label: '交车车型', value: orderInfoVal.modelName },
      { label: '订单来源', value: orderInfoVal.orderSourceName },
    ]
  })

  // 下一步是否可点击
  const nextStepIsValid = computed(() => {
    // 需要判断必填项是否均填写
    let formValue = form.value
    // 合同信息
    if (formValue.contractList?.length > 0) {
      let contract = formValue.contractList[0]
      if (contract.fileId) {
        if (!contract.contractNo) {
          return false
        }
      }
    }
    return true
  })

  const priceTemplateId = ref()
  const feeFormRef = ref()
  const feeForm = ref({
    randomKey: 0,
    orderFee: [
      {
        // 费用类型（线上费用|线下费用）
        feeType: 1,
        feeDetailList: [],
        priceTemplateId: priceTemplateId,
        feeDetailTypeList: ['basicFee', 'addServiceFee', 'preferentialFee', 'otherFee'],
      },
    ],
  })
  provide('feeForm', feeForm)

  // 实时费用信息开始
  const feeRealtimeSum = computed(() => {
    let orderFee = feeForm.value.orderFee
    if (orderFee) {
      let feeVal = buildTreeData(orderFee)
      let feeTreeStData = processTreeData(feeVal)
      let sum = 0
      feeTreeStData.forEach((item) => {
        sum = decimalAddition(sum, item.value)
      })
      return sum
    }
    return 0
  })

  // 初始化
  const cacheStoreTemplate = ref({})
  const init = () => {
    // 获取订单详情
    getOrdrDetailsAPI({ id: orderId.value }).then((res) => {
      const result = res.result
      orderInfo.value = result.orderInfo

      // 初始化续租后还车时间为当前结束时间 + 1 天
      let endTime = orderInfo.value.expectedReturnCarTime
      if (endTime) {
        form.value.endTime = dayjs(endTime).add(1, 'day').format('YYYY-MM-DD HH:mm:ss')
      }

      // 读取门店模板配置
      getStoreTemplateDetail(orderInfo.value.siteId, 2, (storeTemplate, templateId) => {
        cacheStoreTemplate.value = storeTemplate
        let feeValue = feeForm.value
        initFeeDetail(feeValue, storeTemplate)
        // 更新费用模板 id
        priceTemplateId.value = templateId
        // 计算租期
        calcRentDays()
      })
    })
  }

  // 获取默认费用
  const calcRate = ref()
  const setDefaultFee = () => {
    const param = {
      id: form.value.id,
      siteId: orderInfo.value.siteId,
      modelId: orderInfo.value.originalModelId,
      endTime: form.value.endTime,
      type: 3,
    }
    calcPriceAPI(param).then((res) => {
      const { basePrice, otherPrice, rate } = res.result
      calcRate.value = rate
      let feeValue = feeForm.value
      let feeDetailList = feeValue.orderFee[0].feeDetailList
      // 处理增值服务费默认值
      handleAddserviceDefaultFee(feeDetailList, cacheStoreTemplate.value, rate)
      // 初始化其他费用
      feeDetailList.forEach((feeCategory) => {
        const { childrenList } = feeCategory
        // 默认系统计算的费用包含，基础费用，押金费用以及增值服务费中的例如上门取车费、夜间服务费等费用
        if (childrenList && childrenList.length > 0) {
          childrenList.forEach((feeItem) => {
            // 费用名称
            let feeName = feeItem.itemName
            // basicPrice 费用
            if (feeName == '月租价（标准）') {
              if (basePrice?.price >= 0) feeItem.amount = basePrice?.price
            }
            if (feeName == '手续费') {
              if (basePrice?.poundageAmount >= 0) feeItem.amount = basePrice?.poundageAmount
            }
            if (feeName == '手续费（标准）') {
              if (basePrice?.poundageAmount >= 0) feeItem.amount = basePrice?.poundageAmount
            }
            if (feeName == '基础保险（标准）') {
              if (basePrice?.insuranceAmount >= 0) feeItem.amount = basePrice?.insuranceAmount
            }
            // otherPrice 费用
            if (otherPrice && otherPrice.length > 0) {
              let findIndex = otherPrice.findIndex((item) => item.itemName == feeName)
              if (findIndex >= 0) {
                let fee = otherPrice[findIndex]
                feeItem.statics = true
                if (fee?.amount >= 0) {
                  feeItem.amount = fee.amount
                }
              }
            }
          })
        }
      })
      // 当没有下单车型时，此时费用计算不会计算出下述几种费用，此时需要手动补充费用，补充0
      if (!basePrice) {
        feeDetailList.forEach((feeCategory) => {
          const { childrenList } = feeCategory
          if (childrenList && childrenList.length > 0) {
            childrenList.forEach((feeItem) => {
              // 费用名称
              let feeName = feeItem.itemName
              // basicPrice 费用
              if (['月租价（标准）', '车辆租金', '手续费（标准）', '手续费', '基础保险', '基础保险（标准）'].includes(feeName)) {
                feeItem.amount = 0
              }
            })
          }
        })
      }
    })
  }
  // 计算租期
  const leaseNumberStr = ref()
  const leaseMonthsNumber = ref()
  const calcRentDays = () => {
    let startTime = orderInfo.value.expectedReturnCarTime
    startTime = dayjs(startTime).add(1, 'days').format('YYYY-MM-DD 00:00:00')
    let value = form.value.endTime
    if (value) {
      // 计算租期
      const param = {
        expectedUseCarTime: startTime,
        expectedReturnCarTime: value,
      }
      computeRentDayAPI(param).then((res) => {
        let result = res.result
        let dateStr = result.dateStr
        leaseNumberStr.value = dateStr
        leaseMonthsNumber.value = result.months
        form.value.leaseNumberStr = dateStr
      })
      setDefaultFee()
    } else {
      leaseNumberStr.value = undefined
      form.value.leaseNumberStr = undefined
    }
  }
  // 点击下一步
  const stepClickFn = () => {
    // 当前 step
    let currStep = activeStepListIndex.value
    // 切换到第二步
    if (currStep == 0) {
      formRef.value.validate((valid, errors) => {
        if (valid) {
          // 页面滚动到错误位置
          activeStepListIndex.value = 1
          scrollToTopFn()
          getPrevFeeInfo()
        } else {
          foldValidate(errors, true)
        }
      })
    } else {
      activeStepListIndex.value = 0
      scrollToTopFn()
    }
  }
  // 获取原费用信息
  const prevFeeForm = ref({})
  // 原费用合计
  const originSumInfo = ref({
    sum: 0,
    feeList: [],
  })
  const getPrevFeeInfo = () => {
    // 获取原费用信息
    getOrdrFeeDetailAPI({ id: orderId.value }).then((res) => {
      const result = res.result
      const orderFeeList = result.orderFeeList
      if (orderFeeList?.length > 0) {
        let rentFee = orderFeeList.find((item) => item.feeNameId == 1)
        prevFeeForm.value = {
          orderFee: [
            {
              // 费用类型（线上费用|线下费用）
              feeDetailList: [],
              feeDetailTypeList: ['basicFee', 'addServiceFee', 'preferentialFee', 'otherFee'],
            },
          ],
        }
        // 创建费用时的费用模板快照
        let priceTemplateSnapshot = rentFee.priceTemplateSnapshot
        // 解析后的费用模板
        let storeTemplate = null
        if (priceTemplateSnapshot) {
          priceTemplateSnapshot = JSON.parse(priceTemplateSnapshot)
          storeTemplate = handleStoreTemplateDetail(priceTemplateSnapshot)
        }
        initFeeDetail(prevFeeForm.value, storeTemplate)
        // 回显费用
        let feeDetailList = rentFee.feeDetailList
        let formfeeDetailList = prevFeeForm.value.orderFee[0].feeDetailList
        formfeeDetailList.forEach((formFeeDetailItem) => {
          let findResult = feeDetailList.find((item) => {
            let sameFeeCategory = item.feeCategory == formFeeDetailItem.feeCategory
            let sameFeeName = item.itemName == formFeeDetailItem.feeName
            return sameFeeCategory || sameFeeName
          })
          if (findResult) {
            formFeeDetailItem.categoryType = findResult.type
          } else {
            formFeeDetailItem.categoryType = 0
          }
          formFeeDetailItem.childrenList?.forEach((item) => {
            let findFeeDetail = findResult?.childrenList.find((feeDetailItem) => feeDetailItem.itemName == item.itemName)
            if (!findFeeDetail) {
              findFeeDetail = feeDetailList.find((feeDetailItem) => feeDetailItem.itemName == item.itemName)
            }
            if (findFeeDetail) {
              item.amount = findFeeDetail.amount
              item.id = findFeeDetail.id
              item.statics = true
            }
          })
        })

        let processedData = buildTreeData(prevFeeForm.value.orderFee)
        if (processedData) {
          processedData = processTreeData(processedData)
        }
        originSumInfo.value.feeList = processedData
        // 计算合计
        let sum = 0
        processedData.forEach((item) => {
          sum = decimalAddition(sum, item.value)
        })
        originSumInfo.value.sum = sum
      }
    })
  }
  // 页面滚动到顶部
  const scrollToTopFn = () => {
    uni.pageScrollTo({
      scrollTop: 0,
      duration: 200,
    })
  }
  // 续租
  const okLoading = ref(false)
  const reletFn = () => {
    let feeFormValue = feeForm.value
    let costInfo = buildCostInfoParam(feeFormValue)
    const param = {
      ...form.value,
      orderFee: costInfo.orderFee[0],
      contractAmount: feeRealtimeSum.value,
    }
    // 合同-信息
    let contractList = form.value.contractList
    param.contractFileId = contractList[0].contractFileId
    param.contractNo = contractList[0].contractNo
    param.contractName = contractList[0].contractFileName
    delete param.contractList
    // 处理分期信息
    // 分期总金额不大于0 或 续租时长不大于一个月，分期强制改为全款
    if (feeRealtimeSum.value <= 0 || leaseMonthsNumber.value <= 0) {
      param.paymentScheme = 1
    }
    okLoading.value = true
    reletOrderAPI(param).then(() => {
      confirmVisible.value = false
      useToast({
        title: '续租成功',
      })
        .then(() => {
          useLoadDataAndHotUpdateNavigateBack()
        })
        .catch(() => {
          okLoading.value = false
        })
    })
  }
  // 排车校验
  const resultMsg = ref([])
  const confirmVisible = ref(false)
  const platoonCarVerify = (callback) => {
    const params = {
      refId: orderInfo.value.id,
      startTime: orderInfo.value.expectedReturnCarTime,
      endTime: form.value.endTime,
      useType: 3,
      carId: orderInfo.value.carId,
    }
    platoonCarCheckAPI(params).then((res) => {
      let msgList = res.result.resultMsg || []
      if (msgList.length) {
        resultMsg.value = msgList
        confirmVisible.value = true
        return
      }
      callback && callback()
    })
  }
  // 二次询问确认
  const confirmSubmit = () => {
    reletFn()
  }
  // 确认续租
  const submitFn = () => {
    feeFormRef.value.validate((valid, errors) => {
      if (valid) {
        platoonCarVerify(() => {
          reletFn()
        })
      } else {
        // 页面滚动到错误位置
        foldValidate(errors, true)
      }
    })
  }
</script>
<style lang="less" scoped>
  .container {
    display: flex;
    flex-direction: column;
    background: #f7f8fa;
    .step-wrap {
      border-top: 2rpx solid #f7f8fa;
      background-color: #ffffff;
      z-index: 9;
      position: fixed;
      width: 100%;
      left: 0;
    }
    .order-relet-content {
      padding: 24rpx;
      padding-top: 178rpx;
    }
  }
  .lease-period-rentdays {
    font-size: 30rpx;
    color: #3072f6;
    margin-top: 8rpx;
  }
  .rent-days {
    font-size: 30rpx;
    text-align: right;
    color: #3072f6;
  }

  .fee-pane-content {
    /deep/ .ve-card-content {
      padding-bottom: 0;
    }
  }
  #footer-box {
    position: fixed;
    bottom: 0;
    left: 0;
    width: 100%;
    z-index: 999;
  }
</style>
